"""
注册
"""
import base64
import json
import random

# 获取验证码的url
import re
import time
import traceback

import facade
import parsel
import requests
from parsel import Selector
from xjlibrary.mdatetime.mtime import MDateTime
from xjlibrary.our_file_dir import BaseDir
from xjlibrary.user_pwd.get_user_pwd import UserPwd


# import re
# import http.client
#

#
# http.client._is_legal_header_name = re.compile(rb'\A[^\s][^\r\n]*\Z').fullmatch


class Register(object):
    def __init__(self):
        self.is_stat = 0
        self.emailtype = 0
        self.header1 = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            # "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Pragma": "no-cache",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        self.citydicts = {"110000": "北京市",
                          "120000": "天津市",
                          "130000": "河北省",
                          "140000": "山西省",
                          "150000": "内蒙古自治区",
                          "210000": "辽宁省",
                          "220000": "吉林省",
                          "230000": "黑龙江省",
                          "310000": "上海市",
                          "320000": "江苏省",
                          "330000": "浙江省",
                          "340000": "安徽省",
                          "350000": "福建省",
                          "360000": "江西省",
                          "370000": "山东省",
                          "410000": "河南省",
                          "420000": "湖北省",
                          "430000": "湖南省",
                          "440000": "广东省",
                          "450000": "广西壮族自治区",
                          "460000": "海南省",
                          "500000": "重庆市",
                          "510000": "四川省",
                          "520000": "贵州省",
                          "530000": "云南省",
                          "540000": "西藏自治区",
                          "610000": "陕西省",
                          "620000": "甘肃省",
                          "630000": "青海省",
                          "640000": "宁夏回族自治区",
                          "650000": "新疆维吾尔自治区",
                          "710000": "台湾",
                          "810000": "香港特别行政区",
                          "820000": "澳门特别行政区"
                          }
        curPath = BaseDir.get_file_dir_absolute(__file__)
        configfile = BaseDir.get_new_path(curPath, "db.ini")
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=facade.get_streamlogger())
        self.Headers = {
            'Accept': '*/*',
            'Referer': 'https://10minutemail.net/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
        }
        self.init()

    def init(self):
        self.city = ""
        self.city2 = ""
        self.email = ""
        self.code = ""
        self.user = ""
        self.pwd = ""
        self.j_user = ""
        self.j_pwd = ""
        self.url_get_code = ""
        # requests.session()
        self.sn = requests.Session()
        self.sn1 = requests.Session()
        self.cookies = None

    def get_city(self):
        urlcity = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showProvince.shtml"
        headercity = self.header1
        self.city = random.sample(self.citydicts.keys(), 1)
        postcity = {
            "areaCode": self.city
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(urlcity,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          data=postcity,
                                                          endstring="",
                                                          headers=headercity,
                                                          timeout=30
                                                          )
        if BoolResult:
            dicts = json.loads(r.text)
            listc = dicts["areaCodeList"]
            dictsc = {}
            for ones in listc:
                dictsc[ones["code"]] = ones["codeName"]
            self.city2 = random.sample(dictsc.keys(), 1)
        else:
            print("获取错误")

    def get_email(self):
        """
        获取一个临时邮箱
        :return:
        """
        if self.emailtype == 0:
            reg.email = input("please input email:")
            return True
        elif self.emailtype == 1:
            self.user, self.pwd = UserPwd.get_userNameAndPassword()
            self.email_regx = ['@linshiyouxiang.net', '@iffymedia.com', '@figurescoin.com', '@payspun.com',
                               '@beluckygame.com', '@thrubay.com', '@claimab.com', '@bestsoundeffects.com',
                               '@profast.top', '@icemail.club', '@vradportal.com', '@themegreview.com']
            regx = random.choice(self.email_regx)
            reg.email = self.user + regx
            start = int(time.time())
            url = "https://www.linshiyouxiang.net/api/v1/mailbox/keepalive?force_change=1&mailbox={}&_ts={}".format(
                self.user, start)
            headers = {
                "accept": "*/*",
                "accept-encoding": "gzip, deflate",
                "accept-language": "zh-CN,zh;q=0.9",
                "cache-control": "no-cache",
                "pragma": "no-cache",
                "referer": "https://www.linshiyouxiang.net/",
                # "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "x-requested-with": "XMLHttpRequest"
            }
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          mark="",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )
            if BoolResult:
                pass
            else:
                print("初始化请求失败")
                return False

            url = "https://www.linshiyouxiang.net/"
            headers = {
                "cache-control": "no-cache",
                "pragma": "no-cache",
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "accept-encoding": "gzip, deflate",
                "accept-language": "zh-CN,zh;q=0.9",
                "referer": "https://www.linshiyouxiang.net/",
                # "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "upgrade-insecure-requests": "1"

            }
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          mark="",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )
            if BoolResult:
                return True
            else:
                return False

        else:
            url = "https://10minutemail.net/"
            header = {
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Encoding": "gzip, deflate",
                "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
                # "upgrade-insecure-requests": "1",
                "Cache-Control": "no-cache",
                "Content-Type": "application/x-www-form-urlencoded"
            }
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          # proxies=self.proxys,
                                                          headers=header,
                                                          verify=False,
                                                          timeout=30)
            if BoolResult:
                self.cookies = r.cookies.get_dict()
                selector = Selector(text=r.text)
                self.email = selector.xpath('//*[@id="fe_text"]/@value').get()
                print("解析出来的email：{}".format(self.email))
                return True
            else:
                print("获取10分钟邮箱失败")
                return False

    def send_eamil_code(self):
        """
        获取邮箱验证码
        :return:
        """
        self.get_ip()
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-checkEmailIsExist.shtml"
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        postdate = {
            "email": self.email
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          data=postdate,
                                                          verify=False,
                                                          endstring="",
                                                          timeout=(30, 60))
        if BoolResult:
            # 值为1和2都不正确
            checkemail = json.loads(r.text)["isExistEmail"]
            print("检查email的值为:{}".format(checkemail))
            if not checkemail:
                print("检查邮件成功")
            else:
                print("1、邮箱存在或者 2、邮箱后缀被禁")
                return False
        else:
            print("check 失败")
            return False
        self.get_ip()
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/recordSendMail-recordMailTime.shtml"
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          verify=False,
                                                          endstring="",
                                                          timeout=(30, 60))
        if BoolResult:
            print(r.text)
            print("第二请求成功")
        else:
            print("第二请求失败")
            return False

        self.get_ip()

        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-generateEmailCode.shtml"
        postdate = {
            "email": self.email
        }
        print(postdate)
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=self.header1,
                                                          verify=False,
                                                          data=postdate,
                                                          endstring="",
                                                          mark="email",
                                                          timeout=30
                                                          )
        if BoolResult:

            dicts = json.loads(r.text)
            print(dicts["sendSuccess"])
            if dicts["sendSuccess"] == "true" or dicts["sendSuccess"] == "True" or dicts["sendSuccess"] is True:
                print("发送验证码成功")
                return True
            else:
                print(dicts)
                print("send email err")
                return False
        else:
            print("发送验证码失败")
            return False

    def get_email_code(self):
        """
        收取邮件
        :return:
        """
        if self.emailtype == 0:
            return True
        elif self.emailtype == 1:
            time.sleep(10)
            url = "https://www.linshiyouxiang.net/api/v1/mailbox/keepalive"
            header = {
                "accept": "*/*",
                "accept-encoding": "gzip, deflate",
                "accept-language": "zh-CN,zh;q=0.9",
                "cache-control": "no-cache",
                "pragma": "no-cache",
                "referer": "https://www.linshiyouxiang.net/",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "x-requested-with": "XMLHttpRequest"

            }
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          proxies=self.proxys,
                                                          headers=header,
                                                          mark="",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )
            if BoolResult:
                print("keepalive success")
            else:
                return False
            url = "https://www.linshiyouxiang.net/api/v1/mailbox/" + self.user
            header = {
                "accept": "application/json, text/javascript, */*; q=0.01",
                "accept-encoding": "gzip, deflate",
                "accept-language": "zh-CN,zh;q=0.9",
                "referer": "https://www.linshiyouxiang.net/",
                # "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "x-requested-with": "XMLHttpRequest"
            }

            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          proxies=self.proxys,
                                                          headers=header,
                                                          mark="专利检索及分析系统",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )
            print(r.text)

            if BoolResult:
                print(r.text)
                self.url_get_code = ""
                self.url_get_code = json.loads(r.text)[0]["id"]
                self.url_get_code2 = json.loads(r.text)[0]["mailbox"]
                if self.url_get_code:
                    return True
                else:
                    return False

            else:
                return False


        else:

            times = int(time.time() * 1000)
            url = "https://10minutemail.net/mailbox.ajax.php?_={}".format(times)
            header = {
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Encoding": "gzip, deflate",
                "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Type": "application/x-www-form-urlencoded"
            }
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          # proxies=self.proxys,
                                                          headers=header,
                                                          mark="pss-system@pss-system.gov.cn",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )
            if BoolResult:
                parsel1 = parsel.Selector(text=r.text)
                list1 = parsel1.xpath("//table//tr").getall()
                for tr in list1:
                    if tr.find("专利检索及分析系统") > -1:
                        url = parsel.Selector(tr).xpath(".//tr/@onclick").get()
                        # location='readmail.html?mid=ikAdXw'
                        url = url.replace("location='", "").replace("'", "")
                        self.url_get_code = url
                        print(r.text)
                        return True
                return False
            else:
                print(r.text)
                print("没有专利验证码,睡10秒 继续等待")
                time.sleep(10)
                return False

    def get_code_para(self):
        if self.emailtype == 0:
            reg.code = input("please input code:")
            return True
        elif self.emailtype == 1:
            url = "https://www.linshiyouxiang.net/mailbox/{}/{}".format(self.url_get_code2, self.url_get_code)
            headers = {
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "accept-encoding": "gzip, deflate",
                "accept-language": "zh-CN,zh;q=0.9",
                "referer": "https://www.linshiyouxiang.net/",
                # "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
                "upgrade-insecure-requests": "1"
            }
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          sn=self.sn1,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          mark="",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )
            if BoolResult:
                searchObj = re.search(r"邮件验证码为： (.*?) ，请尽快完成", r.text, flags=0)
                self.code = searchObj.group(1)
                self.code = self.code.strip()
                print("code is :{}".format(self.code))
                return True
        else:
            fullurl = "https://10minutemail.net/" + self.url_get_code
            headers = {
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "accept-encoding": "gzip, deflate",
                "accept-language": "zh-CN,zh;q=0.9",
                "referer": "https://10minutemail.net/",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
            }
            BoolResult, errString, r = facade.BaseRequest(fullurl,
                                                          sn=self.sn1,
                                                          # proxies=self.proxys,
                                                          headers=headers,
                                                          mark="",
                                                          endstring="",
                                                          verify=False,
                                                          timeout=30
                                                          )

            if BoolResult:
                parsel2 = parsel.Selector(text=r.text)
                list2 = parsel2.xpath('//*[@id="tab1"]/div/text()').get()
                self.code = list2.replace("尊敬的用户您好， 您申请注册的【专利检索及分析系统】邮件验证码为：", "").replace("，请尽快完成注册。", "")
                self.code = self.code.strip()
                print("code is :{}".format(self.code))
                return True
            else:
                print(r.text)
                print("请求验证码失败")
                return False

    # def get_email_befor(self):
    #     url = "https://m.addthis.com/live/red_lojson/100eng.json?sh=0&ph=1588&ivh=613&dt=156816&pdt=722&ict=&pct=0&perf=widget%7C723%7C1519%2Clojson%7C9077%7C544%2Csh%7C9084%7C538&rndr=render_toolbox%7C9746%2Crender_layers_share%7C9857%2Crender_layers_thankyou%7C9885&cmenu=null&ppd=0&ppl=0&fbe=&xmv=0&xms=0&xmlc=0&jsfw=jquery%2Cgoogleanalytics&jsfwv=jquery-1.11.3%2Cgoogleanalytics-analytics.js&al=men%2Csmlsh%2Csmlty&scr=4&scv=0&apiu=3&ba=3&sid=5c90ab31d2873859&rev=v8.4.0-wp&pub=ra-533ad66e6b4d166d&dp=10minutemail.org&fp=&pfm=0&icns=qzone%2Csinaweibo%2Ctencentweibo%2Cwechat%2Cfacebook%2Ctwitter%2Caddthis"
    #     header = {
    #         "Content-Type": "text/plain;charset=UTF-8",
    #         "Origin": "https://10minutemail.org",
    #         "Referer": "https://10minutemail.org/",
    #         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
    #     }
    #     BoolResult, errString, r = facade.BaseRequest(url, headers=header, endstring="", sn=self.sn)
    #     url = "https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4868759087006546&output=html&h=188&slotname=2966615376&adk=3722450892&adf=4187687044&w=728&lmt=1552985046&rafmt=12&guci=2.2.0.0.2.2.0.0&format=728x188&url=https%3A%2F%2F10minutemail.org%2F&flash=0&wgl=1&adsid=NT&dt=1552985045486&bpp=31&bdt=2218&fdt=645&idt=643&shv=r20190313&cbv=r20190131&saldr=aa&abxe=1&correlator=1414463922173&frm=20&pv=2&ga_vid=483465663.1552985046&ga_sid=1552985046&ga_hid=1960497234&ga_fc=0&iag=0&icsg=4503595545136672&dssz=45&mdo=0&mso=0&u_tz=480&u_his=22&u_java=0&u_h=900&u_w=1440&u_ah=870&u_aw=1440&u_cd=24&u_nplug=3&u_nmime=4&adx=348&ady=210&biw=1423&bih=768&scr_x=0&scr_y=0&eid=21060853&oid=3&ref=https%3A%2F%2F10minutemail.org%2F&rx=0&eae=0&fc=1936&brdim=0%2C0%2C0%2C0%2C1440%2C0%2C1440%2C870%2C1440%2C768&vis=1&rsz=%7C%7CeoE%7C&abl=CS&ppjl=f&pfx=0&fu=280&bc=15&osw_key=2551605040&ifi=1&uci=1.ykj9606ro31&fsb=1&xpc=qkelcwJcgR&p=https%3A//10minutemail.org&dtd=683"
    #     BoolResult, errString, r = facade.BaseRequest(url, headers=header, endstring="", sn=self.sn)

    def register(self):

        url1 = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-checkUserName.shtml"
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        postdate = {
            "userNameForCheck": "{}".format(self.user)
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(url1,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          data=postdate,
                                                          verify=False,
                                                          endstring="",
                                                          timeout=(30, 60))
        if BoolResult:
            exist = json.loads(r.text)["exist"]
            if exist == "true" or exist == "True" or exist is True:
                print("存在")
                return False
            else:
                print("检查用户成功")
        else:
            print("检查用户失败")
            return False
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-checkEmailIsExist.shtml"
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        postdate = {
            "email": "{}".format(self.email)
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          data=postdate,
                                                          verify=False,
                                                          endstring="",
                                                          timeout=(30, 60))
        if BoolResult:
            # 值为1和2都不正确
            checkemail = json.loads(r.text)["isExistEmail"]
            print("检查email的值为:{}".format(checkemail))
            if not checkemail:
                print("检查邮件成功")
            else:
                print("1、邮箱存在或者 2、邮箱后缀被禁")
                return False
        else:
            print("检查邮件失败")
            return False
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-checkEmailCode.shtml"
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        postdate = {
            "validateEmailCode": self.code
        }
        print(postdate)
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(url,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=headers,
                                                          data=postdate,
                                                          verify=False,
                                                          endstring="",
                                                          timeout=(30, 60))
        if BoolResult:
            print("检查code成功")
        else:
            print(r.text)
            print("检查code失败")
            return False
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/app/uilogin/js/base64.js?_={}".format(
            str(int(time.time() * 1000)))
        headers = {
            "Accept": "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Host": "pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=self.sn,
                                                      proxies=self.proxys,
                                                      headers=headers,
                                                      verify=False,
                                                      endstring="",
                                                      timeout=(30, 60))
        if BoolResult:
            print("检查js成功")
        else:
            print("检查js失败")
            return False
        urlre = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-register123123.shtml"

        headerre = {
            "Accept": "ttext/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": "pss-system.cnipa.gov.cn",
            "Origin": "http://pss-system.cnipa.gov.cn",
            "Pragma": "no-cache",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
        }
        self.user, self.pwd = UserPwd.get_userNameAndPassword()
        # self.user = self.email.split("@")[0]
        self.j_user = str(base64.b64encode(bytes(self.user, encoding='utf-8')), encoding="utf-8")
        self.j_pwd = str(base64.b64encode(bytes(self.pwd, encoding='utf-8')), encoding="utf-8")
        self.email1 = str(base64.b64encode(bytes(self.email, encoding='utf-8')), encoding="utf-8")
        self.get_city()
        postdatere = {
            "afterRegUrl": "",
            "wee.bizlog.modulelevel": "0101402",
            "validateEmailCode": "{}".format(self.code),
            "userAccount.user.extendInfo.province": self.city[0],
            "userAccount.user.extendInfo.city": self.city2[0],
            "userAccount.user.description": "0",
            "userAccount.account.username": self.j_user,
            "userAccount.account.password": self.j_pwd,
            "userAccount.user.email": self.email1,
            "userAccount.user.extendInfo.mobile": ""
        }
        print(postdatere)
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequestPost(urlre,
                                                          sn=self.sn,
                                                          proxies=self.proxys,
                                                          headers=headerre,
                                                          data=postdatere,
                                                          timeout=(30, 60),
                                                          verify=False,
                                                          endstring="",
                                                          mark="欢迎访问专利检索及分析"
                                                          )

        if BoolResult:
            print("注册成功")
            return True
        else:
            print("注册失败")
            return False

    def set_proxy(self, num):
        """
        为请求设置代理
        :param proxy:
        :return:
        """
        if num == 0:
            self.proxys = None
            return True
        if num == 1:
            list1 = [
                '192.168.30.176:8120',
                '192.168.30.176:8119',
                '192.168.30.176:8184',
                '192.168.30.176:8207',
                '192.168.30.176:8030',
                '192.168.30.176:8135',
                '192.168.30.176:8012',
                '192.168.30.176:8033',
                '192.168.30.176:8004',
                '192.168.30.176:8171',
                '192.168.30.176:8031',
                '192.168.30.176:8160',
                '192.168.30.123:8081',
                '192.168.30.176:8165',
                '192.168.30.176:8041',
                '192.168.30.176:8098',
                '192.168.30.176:8231',
                '192.168.30.176:8140',
                '192.168.30.176:8082',
                '192.168.30.176:8182',
                '192.168.30.176:8189',
                '192.168.30.176:8021',
                '192.168.30.176:8149',
                '192.168.30.176:8243',
                '192.168.30.176:8195',
                ]
            # list1 = ["182.92.105.136:3128","120.210.219.104:80","120.210.219.105:80","124.202.166.171:82","13.56.2.56:8090","159.138.1.185:80","159.138.20.247:80","159.138.21.170:80","159.138.3.119:80","159.138.5.222:80","162.243.102.207:3128","120.210.219.102:80","200.255.122.174:8080","222.110.147.50:3128","35.235.75.244:3128","39.137.107.98:80","39.137.107.98:8080","39.137.77.66:80","39.137.77.66:8080","49.51.68.122:1080","49.51.70.42:1080","91.205.218.32:80","117.191.11.72:8080","117.191.11.103:8080","117.191.11.105:80","117.191.11.105:8080","117.191.11.106:80","117.191.11.106:8080","117.191.11.107:80","117.191.11.107:8080","117.191.11.71:80","117.191.11.71:8080","117.191.11.72:80","117.191.11.103:80","117.191.11.73:80","117.191.11.73:8080","117.191.11.74:80","117.191.11.74:8080","117.191.11.75:80","117.191.11.75:8080","118.24.182.249:8081","120.210.219.101:80","120.210.219.101:8080"]
            proxy1 = random.choice(list1)
            self.proxys = {
                "http": "http://%(ip)s/" % {'ip': proxy1},
                "https": "http://%(ip)s/" % {'ip': proxy1}
            }
            return True
        elif num == 2:
            sql = "select `proxy`,`update_time`,`source` from `proxy_pool` where `source`='kuaidaili' and stat in (1,2) order by update_time ASC limit 5;"
            statrows = reg.mysqlutils.SelectFromDB(sql)
            row = random.choice(statrows)
            proxy = row[0]
            self.proxys = {
                "http": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "2660438158", 'pwd': "171uz572",
                                                             'ip': proxy},
                "https": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "2660438158", 'pwd': "171uz572",
                                                              'ip': proxy}
            }
            return True
        elif num == 3:
            sql = "select `proxy`,`update_time`,`source` from `proxy_pool` where `source`='mimvp' and stat in (0,2) order by RAND() limit 5;"
            statrows = reg.mysqlutils.SelectFromDB(sql)
            if not statrows:
                return False
            row = random.choice(statrows)
            proxy = row[0]
            self.proxys = {
                "http": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "5718b2086b52", 'pwd': "qvyvrcwfvg",
                                                             'ip': proxy},
                "https": "http://%(user)s:%(pwd)s@%(ip)s/" % {'user': "5718b2086b52", 'pwd': "qvyvrcwfvg",
                                                              'ip': proxy}
            }
            print(self.proxys)
            return True
        elif num == 4:
            print(4)
            self.proxys = {
                "http": "http://lum-customer-hl_bd46d5e0-zone-static:o61ibg9eghso@zproxy.lum-superproxy.io:22225",
                "https": "http://lum-customer-hl_bd46d5e0-zone-static:o61ibg9eghso@zproxy.lum-superproxy.io:22225"
            }
            return True
        elif num == 5:
            proxy1 = "115.219.72.189:4207"
            self.proxys = {
                "http": "http://%(ip)s/" % {'ip': proxy1},
                "https": "http://%(ip)s/" % {'ip': proxy1}
            }
            return True

    def get_ip(self):
        return True
        url = "http://ip.42.pl/raw"
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=self.sn,
                                                      proxies=self.proxys,
                                                      endstring="",
                                                      allow_redirects=True,
                                                      timeout=(20, 60))
        if BoolResult:
            print(r.text)

    def check_proxys_is_used(self):
        self.get_ip()
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiIndex.shtml"
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Host": "pss-system.cnipa.gov.cn",
            "Pragma": "no-cache",
            "Proxy-Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=self.sn,
                                                      proxies=self.proxys,
                                                      mark="欢迎访问专利检索及分析",
                                                      allow_redirects=True,
                                                      headers=header,
                                                      timeout=(20, 60))
        print("检查代理有效性 {}".format(errString))
        if BoolResult:
            return True
        else:
            return False

    def register_home(self):
        self.get_ip()
        url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml"
        header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Host": "pss-system.cnipa.gov.cn",
            "Referer": "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiregister-showRegisterPage.shtml",
            "Upgrade-Insecure-Requests": "1",
            # "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
        }
        print(self.proxys)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      sn=self.sn,
                                                      proxies=self.proxys,
                                                      endstring="",
                                                      headers=header,
                                                      verify=False,
                                                      timeout=(30, 60))
        if BoolResult:
            pass
        else:
            print("fangwen home err")


if __name__ == "__main__":
    reg = Register()
    reg.proxynum = random.choice([1, 3, 3])
    reg.rownum = random.choice([1, 1, 1, 2, 2])
    while True:
        try:
            reg.sn = requests.Session()
            reg.sn1 = requests.Session()
            usersetstat = MDateTime.get_now_datetime(format="%H%M%S", struct_time=time.localtime(time.time()))
            if usersetstat > "233000":
                reg.is_stat = 0
            if usersetstat < "003000":
                if reg.is_stat == 0:
                    sql = "update `user` set stat=1,isajxcount=0 where stat != -1"
                    print(sql)
                    reg.mysqlutils.ExeSqlToDB(sql)
                    reg.is_stat += 1
            # 输入想设置的代理类型 1，2，3

            if not reg.set_proxy(1):  # (reg.proxynum):  #
                time.sleep(20)
                continue
            reg.emailtype = 0  # reg.rownum
            if not reg.check_proxys_is_used():
                continue

            while True:
                if reg.get_email():
                    pass
                else:
                    time.sleep(20)
                break

            if reg.email:
                time.sleep(5)
                print(reg.email)
                reg.register_home()
                if reg.send_eamil_code():  #
                    start = int(time.time())
                    for i in range(60):
                        if reg.get_email_code():
                            if reg.get_code_para():
                                print("获取code成功")
                                if reg.register():
                                    num = random.choice([5, 5, 5])
                                    sql = "INSERT IGNORE INTO `user`(`username`, `password`, `j_username`, `j_password`,`email` , `updatetime`, `stat`, `timestat`, `isajxcount`, `isajxupdatetime`,`url`) VALUES ('{}', '{}', '{}', '{}','{}', '2019-03-29 17:40:26.667', 1, '{}', 0, '2019-03-20 10:48:32','http://pss-system.cnipa.gov.cn')"
                                    sql = sql.format(reg.user, reg.pwd, reg.j_user, reg.j_pwd, reg.email, num)
                                    print(sql)
                                    reg.mysqlutils.ExeSqlToDB(sql)
                                    reg.init()
                                    break

                                else:
                                    print("失败")
                                    break
                            else:
                                print("过程失败")
                                break
                else:
                    continue
                """
                else:
                    for i in range(60):
                        print("sleep{}".format(i))
                        time.sleep(3)
                    break
                """
            for i in range(60):
                print("sleep{}".format(i))
                time.sleep(3)
            reg.proxynum = random.choice([1, 3, 3])
            reg.rownum = random.choice([1, 1, 2, 2, 2])

        except:
            print(traceback.format_exc())
            time.sleep(60)
            pass
